import json

import datetime
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.bill.models.bill_instance import BillInstance
from app.bill.utils.bill_sync_utils import BillSyncUtils
from app.bill.handlers.bill_month_handler import BillMonthHandler


class BillInstanceHandler():
    """  Bill Instance Handler
         账单操作
    """
    def __init__(self):
        self.bill_sync_utils = BillSyncUtils()
        self.bill_month_handler = BillMonthHandler()



    def get_instance_aliyun(self, bill_cycle: str):
        """
        直接从阿里云获取实时账单信息、
        """
        try:
            result = self.bill_sync_utils.get_bill_instance_from_aliyun(bill_cycle)
            if not result:
                logger.warning(f"get bill:{bill_cycle} instance from aliyun failed")
                return False

        except Exception as e:
            message = f"get bill:{bill_cycle} instance from aliyun error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def get_instance_bill_cycle(self, db: Session, page: int, per_page: int):
        """
        账单实例表, 获取数据库里面有哪些账期
        """
        try:
            result = BillInstance.get_bill_cycles(db, page, per_page)
            if not result:
                logger.warning(f"get instance bill cycle failed")
                return False

        except Exception as e:
            message = f"get instance bill cycle error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_match(self, db: Session, bill_cycle: str, page: int, per_page: int, field: str, value: str):
        """
        账期内, 账单实例表, 根据表字段-完全匹配, 获取账单数据
        """
        try:
            result = BillInstance.get_instance_match(db, bill_cycle, page, per_page, field, value)
            if not result:
                logger.warning(f"get instance match failed, bill_cycle:{bill_cycle} {field}:{value}")
                return False

        except Exception as e:
            message = f"get instance match error, bill_cycle:{bill_cycle} {field}:{value}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_search(self, db: Session, bill_cycle: str, page: int, per_page: int, field: str, value: str):
        """
        账期内, 账单实例表, 根据表字段-模糊匹配, 获取账单数据
        """
        try:
            result = BillInstance.get_instance_search(db, bill_cycle, page, per_page, field, value)
            if not result:
                logger.warning(f"get instance search failed, bill_cycle:{bill_cycle} {field}:{value}")
                return False

        except Exception as e:
            message = f"get instance search error, bill_cycle:{bill_cycle} {field}:{value}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def get_instance_account(self, db: Session, bill_cycle: str, page: int, per_page: int):
        """
        账期内, 账单实例表, 根据公司/账号聚合
        """
        try:
            result = BillInstance.get_instance_account(db, bill_cycle, page, per_page)
            if not result:
                logger.warning(f"get instance account failed, bill_cycle:{bill_cycle} {page}:{per_page}")
                return False

        except Exception as e:
            message = f"get instance account error, bill_cycle:{bill_cycle} {page}:{per_page}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_aggregate(self, db: Session, bill_cycle: str, field: str, page: int, per_page: int):
        """
        账期内, 账单实例表, 根据field字段聚合
        """
        try:
            result = BillInstance.get_instance_aggregate(db, bill_cycle, field, page, per_page)
            if not result:
                logger.warning(f"get instance aggregate failed, bill_cycle:{bill_cycle} field:{field} {page}:{per_page}")
                return False

        except Exception as e:
            message = f"get instance aggregate error, bill_cycle:{bill_cycle} field:{field} {page}:{per_page}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_cluster(self, db: Session, bill_cycle: str, bill_class: str, page: int, per_page: int):
        """
        账期内, 账单实例表, 根据集群分类，再按部门聚合
        """
        try:
            result = BillInstance.get_instance_cluster(db, bill_cycle, bill_class, page, per_page)
            if not result:
                logger.warning(f"get instance cluster failed, bill_cycle:{bill_cycle} bill_class:{bill_class} {page}:{per_page}")
                return False

        except Exception as e:
            message = f"get instance cluster error, bill_cycle:{bill_cycle} bill_class:{bill_class} {page}:{per_page}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_cluster_year(self, db: Session, year: str, bill_class: str):
        """
        账期内, 账单实例表, 根据集群分类，再按部门聚合
        """
        try:
            # 获取这一年所有的月份
            months = self.bill_month_handler.get_all_months(year)

            result = BillInstance.get_instance_cluster_year(db, months, bill_class)
            if not result:
                logger.warning(f"get instance cluster year failed, year:{year} bill_class:{bill_class}")
                return False

        except Exception as e:
            message = f"get instance cluster year error, year:{year} bill_class:{bill_class}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_instance_environment(self, db: Session, bill_cycle: str, environment: str, page: int, per_page: int):
        """
        账期内, 账单实例表, 根据环境分类，再按部门聚合
        """
        try:
            result = BillInstance.get_instance_environment(db, bill_cycle, environment, page, per_page)
            if not result:
                logger.warning(f"get instance bill_env failed, bill_cycle:{bill_cycle} environment:{environment} {page}:{per_page}")
                return False

        except Exception as e:
            message = f"get instance bill_env error, bill_cycle:{bill_cycle} environment:{environment} {page}:{per_page}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def start_sys_task(self, db: Session, bill_cycle: str):
        """
        启动同步阿里云账单的异步任务
        """
        try:
            result = self.bill_sync_utils.task_begin(db, bill_cycle)
            if not result:
                logger.warning(f"start sys task failed, bill_cycle:{bill_cycle}")
                return False

        except Exception as e:
            message = f"start sys task error, bill_cycle:{bill_cycle}"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def get_instance_ip_by_bigdata_cluster(self, db: Session, bill_class: str):
        """
        根据获取大数据集群的机器列表ip
        """
        try:
            current_date = datetime.datetime.today() - datetime.timedelta(days=62)
            bill_cycle = current_date.strftime("%Y-%m")
            result = BillInstance.get_instance_ip_by_bigdata_cluster(db, bill_cycle, bill_class)
            if not result:
                logger.error(f"get instance_ip_by_bigdata_cluster failed")
                return False

        except Exception as e:
            message = f"get instance_ip_by_bigdata_cluster failed"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    




